package com.dhh.sky.service;

import java.util.List;
import org.json.JSONObject;
import com.dhh.sky.R;
import com.dhh.sky.SDAApplication;
import com.dhh.sky.model.Operation;
import com.dhh.sky.util.Constant;
import com.dhh.sky.util.JsonKeys;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.LiveOperationListener;
import android.content.Intent;
import android.util.Log;

public class DeleteOperationService extends BasicOperationService{
	public DeleteOperationService(){
		super(Constant.SERVICE_NAME_DELETE);
	}

	@Override
	protected void doOperation(Intent intent){
		message = getString(R.string.msg_error_delete);
		try{
			delete();
		}catch(Exception e){
			Log.e(Constant.TAG, e.getMessage(), e);
		}
	}
	
	private void delete(){
		if(next()){  
			path = op.getTarget();
			doDelete(op.getPath());
			oManager.removeOperation(op.getPath(), Operation.OP_DELETE); 
		}else{
			response(true,message,path);
		}
	}
	
	private boolean next(){
		boolean flag = false;
		List<Operation> ops = oManager.getOperationReady(Operation.OP_DELETE);
		if(ops.size()>0){
			flag = true;
			op = ops.get(0);
			Log.d(Constant.TAG, "Delete next(): "+op.getPath());
		}
		return flag;
	}
	
	private void doDelete(final String id){
		try{
	        mClient = ((SDAApplication) getApplication()).getConnectClient();
	        mClient.deleteAsync(id, new LiveOperationListener(){
				@Override
				public void onComplete(LiveOperation operation) {
					JSONObject result = operation.getResult();
					boolean succ = !result.has(JsonKeys.ERROR);		
					if(succ){
						fManager.delFile(id);
					}else{
						response(false,message,path);
					}
					delete();
				}

				@Override
				public void onError(LiveOperationException exception,LiveOperation operation) {					
					delete();
					response(false,message,path);	
				}
			});		
		}catch(Exception e){
			Log.e(Constant.TAG, e.getMessage(), e);
		}
	}
}
